package com.tastespot.interceptor;

import cn.hutool.http.HttpStatus;
import com.tastespot.model.dto.UserDTO;
import com.tastespot.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 此处是第二层拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截器，用于判断用户是否登录
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserDTO user = UserHolder.getUser();
        if(user == null){
            log.error("用户未登录");
            // 没有，需要拦截，设置状态码
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
        // 有用户，则放行
        return true;
    }
}
